function initNewCategory() {
	var addNew = document.createElement('p');
	addNew.innerHTML = '<a href="#" onclick="javascript:return addNewCategory();">Add a New Category</a>';
	$('extracategories').parentNode.insertBefore(addNew, $('extracategories').nextSibling);
	
	if (!Element.hasClassName($('entrytitle').form, 'editing')) {
		Event.observe($('entrytitle'), 'blur', detectCategories, false);
		
		var categories = $('entrycategories').getElementsByTagName('input');
		for (i=0;i<categories.length;i++) {
			Event.observe(categories[i], 'click', stopDetectingCategories, false);
		}
	}
}

function stopDetectingCategories() {
	Event.stopObserving($('entrytitle'), 'blur', detectCategories, false);
}

function detectCategories() {
	var categories = $('entrycategories').getElementsByTagName('input');
	for (i=0;i<categories.length;i++) {
		if ($('entrytitle').value.toLowerCase().match(categories[i].value.toLowerCase())) {
			categories[i].checked = true;
			Element.addClassName(categories[i].parentNode, 'highlight');
		} else {
			categories[i].checked = false;
			Element.removeClassName(categories[i].parentNode, 'highlight');
		}
	}
}

function addNewCategory(event) {
	var inputfield = document.createElement('input');
	inputfield.type = 'text';
	inputfield.name = 'categories[]';
	
	var removelink = document.createElement('a');
	removelink.appendChild(document.createTextNode('Remove'));
	removelink.href = '#';
	removelink.onclick = removeThisCategory;
	
	var input = document.createElement('span');
	input.appendChild(inputfield);
	input.appendChild(document.createTextNode(' '));
	input.appendChild(removelink);
	input.appendChild(document.createElement('br'));
	
	$('extracategories').appendChild(input);

	return false;
}

function removeThisCategory(event) {
	Element.remove(Event.element(event).parentNode);
	return false;
}

Event.observe(window, 'load', initNewCategory, false);